package com.hyp.pay.http;

import com.hyp.pay.BuildConfig;
import com.hyp.pay.model.BaiduJson;
import com.hyp.pay.model.FindRecharge;
import com.hyp.pay.model.JsonModel;
import com.hyp.pay.model.QQJson;
import com.hyp.pay.model.UpLodAttion;
import com.hyp.pay.model.UplodIdcard;
import com.hyp.pay.model.UserJson;
import com.hyp.pay.utils.SystemUtil;
import com.jakewharton.retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import io.reactivex.subscribers.ResourceSubscriber;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Query;

/**
 * Created by xuwc on 2016/11/24.
 */
public class RetrofitHelper {

    private static OkHttpClient sOkHttpClient = null;
    private static HyqApis sWedApis = null;

    public RetrofitHelper() {
        init();
    }

    private void init() {
        initOkHttp();

        sWedApis = getWedApiService();
    }


    private static void initOkHttp() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
            loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
            builder.addInterceptor(loggingInterceptor);
        }
//        File cacheFile = new File(Constants.PATH_CACHE);
//        Cache cache = new Cache(cacheFile, 1024 * 1024 * 50);
        Interceptor cacheInterceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Request request = chain.request();
                if (!SystemUtil.isNetworkConnected()) {
                    request = request.newBuilder()
                            .cacheControl(CacheControl.FORCE_CACHE)
                            .build();
                }
                Response response = chain.proceed(request);

                if (SystemUtil.isNetworkConnected()) {
                    int maxAge = 0;
                    // 有网络时, 不缓存, 最大保存时长为0
                    response.newBuilder()
                            .removeHeader("Pragma")
                            .build();
                } else {
                    // 无网络时，设置超时为4周
                    int maxStale = 60 * 60 * 24 * 28;
                    response.newBuilder()
                            .removeHeader("Pragma")
                            .build();
                }
                return response;
            }
        };
//        Interceptor apikey = new Interceptor() {
//            @Override
//            public Response intercept(Chain chain) throws IOException {
//                Request request = chain.request();
//                request = request.newBuilder()
//                        .addHeader("appid", Constants.appid)
//                        .addHeader("key", Constants.key)
//                        .build();
//                return chain.proceed(request);
//            }
//        };
        builder.addNetworkInterceptor(cacheInterceptor);
        builder.addInterceptor(cacheInterceptor);
//         builder.addInterceptor(apikey);
//        builder.cache(cache);
        //设置超时
        builder.connectTimeout(10, TimeUnit.SECONDS);
        builder.readTimeout(20, TimeUnit.SECONDS);
        builder.writeTimeout(20, TimeUnit.SECONDS);
        //错误重连
        builder.retryOnConnectionFailure(true);
        sOkHttpClient = builder.build();
    }

    private static HyqApis getWedApiService() {
        Retrofit gankRetrofit = new Retrofit.Builder()
                .baseUrl(HyqApis.HOST)
                .client(sOkHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
        return gankRetrofit.create(HyqApis.class);
    }

    /**
     * 初始化通用的观察者
     *
     * @param observable 观察者
     */
    public ResourceSubscriber startObservable(Flowable observable, ResourceSubscriber subscriber) {
        return (ResourceSubscriber) observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(subscriber);
    }

    //    //微信支付
    public Flowable<String> fetchWeixin(String GoodsName, String Charge, String CreatTime, String Type, String UserId,
                                        String AuthCode, String AddIp) {
        return sWedApis.getWeixin(GoodsName, Charge, CreatTime, Type, UserId, AuthCode, AddIp);
    }

    //支付宝支付
    public Flowable<String> fetchZhiPay(String goods_name, String Charge, String CreatTime, String PayType, String UserId,
                                        String AuthCode, String AddIp) {
        return sWedApis.getZhiPay(goods_name, Charge, CreatTime, PayType, UserId, AuthCode, AddIp);
    }

    //百度支付
    public Flowable<String> fetchBaiduPay(String goods_name, String total_amount, String pay_type,
                                          String addip, String pay_code, String userid) {
        return sWedApis.getBaidu(goods_name, total_amount, pay_type, addip, pay_code, userid);
    }

    //京东支付
    public Flowable<JsonModel> fetchJDPay(String receiverName, String amount, String bankName, String receiverCardNo,
                                          String bankCode, String AddIp) {
        return sWedApis.getSuning(receiverName, amount, bankName, receiverCardNo, bankCode, AddIp);
    }

    //QQ支付
    public Flowable<String> fetchQQPay(String totalFee, String AuthCode, String AddIp, String userid) {
        return sWedApis.getQQPay(totalFee, AuthCode, AddIp, userid);
    }

    //微信查询订单
    public Flowable<String> fetchWeinxinOrder(String order) {
        return sWedApis.getWeixinOrder(order);
    }

    //支付宝查询订单
    public Flowable<String> fetchzhifuOrder(String order) {
        return sWedApis.getZhiPayOrder(order);
    }

    //百度查询订单
    public Flowable<String> fetchBaiduOrder(String order) {
        return sWedApis.getBaiduOrder(order);
    }

    //QQ查询订单
    public Flowable<String> fetchQQOrder(String order, String ip) {
        return sWedApis.getQQOrder(order, ip);
    }


    //上传图片
    public Flowable<String> UploadFile(MultipartBody.Part body, MultipartBody.Part body2, MultipartBody.Part body3,
                                       MultipartBody.Part body4, MultipartBody.Part body5
            , int userid, String orderid) {
        return sWedApis.uploadFile(body, body2, body3, body4, body5, userid, orderid);
    }

    //上传图片
    public Flowable<UplodIdcard> UploadFileIdCard(MultipartBody.Part body, int userid) {
        return sWedApis.uploadFileIdCard(body, userid);
    }

    //    身份证验证
    public Flowable<UpLodAttion> UploadIdCard(String file,String file2, int userid) {
        return sWedApis.uploadIdCard(file, file2, userid);
    }

    //上传头像
    public Flowable<UplodIdcard> UploadFilePicture(MultipartBody.Part body, int userid) {
        return sWedApis.uploadFilePicture(body, userid);
    }

    //    身份证验证
    public Flowable<FindRecharge> findRecharge(String charge) {
        return sWedApis.findHyqAccountRecharge(charge);
    }

    //    身份证验证
    public Flowable<UserJson> findUser(String userid) {
        return sWedApis.findUser(userid);
    }
}
